from micropython import const
from machine import I2C

MAX44009_CONFIGURATION		= const(0x02)
MAX44009_LUX_READING_HIGH   = const(0x03)

MAX44009_CFG_MANUAL         = const(0x40)

class MAX44009:
	def __init__(self, i2c, addr=0x4A):
		if i2c is None or i2c.__class__ != I2C:
			raise ValueError("I2C object needed as argument!")
		self._i2c = i2c
		self._addr = addr

	def setAuto(self):
		_config = self._i2c.readfrom_mem(self._addr, MAX44009_CONFIGURATION, 1)
		_newconfig = _config[0] & (~MAX44009_CFG_MANUAL)
		self._i2c.writeto_mem(self._addr, MAX44009_CONFIGURATION, bytes([_newconfig & 0xFF]))

	def getLux(self):
		_d = self._i2c.readfrom_mem(self._addr, MAX44009_LUX_READING_HIGH, 2)
		_e = _d[0] >> 4
		if (_e == 0x0F):
			return 0

		_m = ((_d[0] & 0x0F) << 4) + (_d[1] & 0x0F)
		_m <<= _e
		return _m * 0.045
		